package com.pactera.madp.cp.service.sync.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import com.pactera.madp.cp.api.entity.crm.WorkPreSavedeptInfoEntity;
import com.pactera.madp.cp.api.entity.sync.SyncPreSavedeptInfoEntity;
import com.pactera.madp.cp.common.constant.Constants;
import com.pactera.madp.cp.common.util.RedisUtil;
import com.pactera.madp.cp.context.SyncStateContext;
import com.pactera.madp.cp.service.WorkPreSavedeptInfoService;
import com.pactera.madp.cp.service.sync.BusiSyncPreSavedeptService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
@AllArgsConstructor
public class BusiSyncPreSavedeptServiceImpl implements BusiSyncPreSavedeptService {

    private final RedisTemplate redisTemplate;
    private final WorkPreSavedeptInfoService workPreSavedeptInfoService;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean syncBusiness() {
        String nowDate = DateUtil.format(new Date(), Constants.DATE_FORMAT);

        // 执行同步业务
        String lockKey = RedisUtil.buildKey(Constants.SYNC_PRE_SAVEDEPT_BUSINESS_LOCK, nowDate);
        try {
            // 获取同步业务的锁
            boolean isLocked = RedisUtil.getLock(lockKey, "1", Constants.EXPIRE_TIME, TimeUnit.SECONDS);
            if (!isLocked) {
                SyncStateContext.get().setSaveLog(false);
                return false;
            }
            log.info("CRM活期业务同步获取锁成功");

            // 获取临时数据
            List<SyncPreSavedeptInfoEntity> syncList = (List<SyncPreSavedeptInfoEntity>) SyncStateContext.get().getTempData()[3];
            if (syncList.isEmpty()) {
                return false;
            }

            List<WorkPreSavedeptInfoEntity> workList = new ArrayList<>();

            WorkPreSavedeptInfoEntity prototype = new WorkPreSavedeptInfoEntity();
            syncList.forEach(s -> {
                WorkPreSavedeptInfoEntity w = prototype.clone();
                BeanUtil.copyProperties(s, w);
                workList.add(w);
            });

            // 清空列表
            syncList.clear();

            if (workList.isEmpty()) {
                return false;
            }

            // 保存当前同步数据到业务表
            workPreSavedeptInfoService.batchSaveOrUpdate(workList);
            // 清空列表
            workList.clear();

            log.info("已同步CRM活期业务数据量：{}", SyncStateContext.get().getTempData()[2]);
        } finally {
            redisTemplate.delete(lockKey);
            log.info("CRM活期业务同步释放锁成功");
        }
        return true;
    }

}
